<template>
  <div class="whole roleWhole">
    <div class="crumbs">
      <a-breadcrumb>
        <a-breadcrumb-item v-for="(item, index) in $route.matched" :key="index">
          <span v-if="index + 1 < $route.matched.length">
            {{
              item.meta.title
            }}
          </span>
          <router-link
              v-if="index + 1 == $route.matched.length"
              :to="item.path"
          >{{ item.meta.title }}
          </router-link>
        </a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <div class="addUser">
      <a-button v-if="addShow" :class="butAdmin" class="userAbut" type="primary" @click="addRole">+ 添加角色</a-button>
    </div>
    <a-table
        :class="TableAdmin"
        :columns="columns"
        :data-source="data"
        :pagination="pagination"
        class="roleTable"
        rowKey="id"
    >
      <span slot="num" slot-scope="text, record, index">
        {{
          (pagination.current - 1) * pagination.pageSize + parseInt(index) + 1
        }}
      </span>
      <template slot="operations" slot-scope="text, record">
        <div class="editable-row-operations">
          <span v-if="delShow && record.id !== '11'">
            <a-popconfirm v-if="data.length" title="确认删除?" @confirm="() => Delete(record.id)">
              <a href="javascript:;" title="删除">
                <a-icon style="color: red; fontsize: 16px" type="delete"/>
              </a>
            </a-popconfirm>
          </span>
          <span class="jiange"></span>
          <span v-if="editShow">
            <a title="编辑" @click="edit(record.id)">
              <a-icon style="color: #7a7d7e; fontsize: 16px" type="edit"/>
            </a>
          </span>
          <span class="jiange"></span>
          <span>
            <a title="授权" @click="impower(record.id)">
              <a-icon style="color: #7a7d7e; fontsize: 16px" type="diff"/>
            </a>
          </span>
        </div>
      </template>
    </a-table>
    <!-- 添加 -->
    <div ref="aModal" class="aModal">
      <a-modal
          v-model="addVisible"
          :getContainer="()=>$refs.aModal"
          :mask="false"
          :maskClosable="false"
          centered
          title="添加角色"
      >
        <template slot="footer">
          <a-button :class="TableButSave" class="butSave" @click="closeAddRole">添加</a-button>
          <a-button :class="TableButReset" class="butReset" @click="addReturnReset">重置</a-button>
        </template>
        <a-form :form="form" class="addForm" hideRequiredMark>
          <a-form-item class="aFormItem" label="角色名称" v-bind="formItemLayout">
            <a-input
                v-decorator="[
            'roleName',
            {
              rules: [
                {
                  required: true,
                  message: '请输入角色名称',
                },
              ],
            },
          ]"
            />
          </a-form-item>

          <a-form-item class="radioStatus aFormItem" label="状态" v-bind="formItemLayout">
            <a-radio-group
                v-decorator="[
            'status',
            {
              rules: [
                {
                  required: true,
                  message: '请选择',
                },
              ],
            },
          ]"
                class="status"
            >
              <a-radio :value="0">正常</a-radio>
              <a-radio :value="1">停用</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="备注" v-bind="formItemLayout">
            <a-textarea
                v-decorator="[
            'remark'
          ]"
                :rows="4"
                style="width: 380px"
            />
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
    <!-- 编辑 -->
    <div ref="aModal1" class="aModal1">
      <a-modal
          v-model="editVisible"
          :getContainer="()=>$refs.aModal1"
          :mask="false"
          :maskClosable="false"
          centered
          title="编辑角色"
      >
        <template slot="footer">
          <a-button :class="TableButSave" class="butSave" @click="closeEditRole">提交</a-button>
          <a-button :class="TableButReset" class="butReset" @click="addReturnReset">重置</a-button>
        </template>
        <a-form :form="form" class="addForm" hideRequiredMark>
          <a-form-item class="aFormItem" label="角色名称" v-bind="formItemLayout">
            <a-input
                v-decorator="[
            'roleName',
            {
              rules: [
                {
                  required: true,
                  message: '请输入角色名称',
                },
              ],
            },
          ]"
            />
          </a-form-item>

          <a-form-item class="radioStatus aFormItem" label="状态" v-bind="formItemLayout">
            <a-radio-group
                v-decorator="[
            'status',
            {
              rules: [
                {
                  required: true,
                  message: '请选择',
                },
              ],
            },
          ]"
                class="status"
            >
              <a-radio :value="0">正常</a-radio>
              <a-radio :value="1">停用</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="备注" v-bind="formItemLayout">
            <a-textarea
                v-decorator="[
            'remark'
          ]"
                :rows="4"
                style="width: 380px"
            />
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
    <!-- 授权 -->
    <div ref="aModalImpower" class="aModalImpower">
      <a-modal
          v-model="impowerVisible"
          :getContainer="()=>$refs.aModalImpower"
          :mask="false"
          :maskClosable="false"
          centered
          title="角色授权"
      >
        <template slot="footer">
          <a-button class="butSave" @click="addImpower(allSelectedNodes)">提交</a-button>
          <a-button class="butReset" @click="cancelImpower">取消</a-button>
        </template>
        <a-tree
            v-if="treeData && treeData.length > 0"
            v-model="checkedKeys"
            :auto-expand-parent="autoExpandParent"
            :checkedKeys="checkedKeys"
            :expanded-keys="expandedKeys"
            :replaceFields="{ key:'id',title:'menuName',children:'children'}"
            :selected-keys="selectedKeys"
            :tree-data="treeData"
            checkable
            class="aTree"
            @check="onBusinessSelectChange"
            @expand="onExpand"
            @select="onSelect"
        />
      </a-modal>
    </div>
  </div>
</template>

<script>
import api from "../../api/roleManagement/roleManagement.js";
import menuApi from "../../api/MenuManagement/MenuManagement.js";

export default {
  data() {
    return {
      formItemLayout: {
        labelCol: {
          xs: {span: 24},
          sm: {span: 8}
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16}
        }
      },
      tailFormItemLayout: {
        wrapperCol: {
          xs: {
            span: 24,
            offset: 0
          },
          sm: {
            span: 16,
            offset: 8
          }
        }
      },
      addVisible: false,
      editVisible: false,
      impowerVisible: false,
      columns: [
        {
          title: "序号",
          dataIndex: "index",
          key: "index",
          scopedSlots: {customRender: "num"},
          width: 78
        },
        {
          title: "角色名称",
          dataIndex: "roleName",
          scopedSlots: {customRender: "roleName"},
          width: 100
        },
        {
          title: "状态",
          dataIndex: "status",
          scopedSlots: {customRender: "status"},
          width: 100
        },
        {
          title: "操作",
          dataIndex: "operations",
          scopedSlots: {customRender: "operations"},
          width: 78
        }
      ],
      Loading: false,
      data: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        defaultPageSize: 10,
        showTotal: total => `共 ${total} 条数据`,
        pageSizeOptions: ["5", "10", "15", "20"],
        onShowSizeChange: current => this.onSizeChange(current),
        onChange: (current, pageSize) => this.onPageChange(current, pageSize)
      },
      addShow: false,
      delShow: false,
      impShow: false,
      editShow: false,

      expandedRowKeys: [],
      menus: [],
      buttons: [],
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      allSelectedNodes: [],
      selectedKeys: [],
      treeData: [],
      tRoleId: '',
      TableAdmin: 'TableAdmin',
      butAdmin: 'butAdmin',
      TableButSave: 'TableButSave',
      TableButReset: 'TableButReset',
      test: []
    };
  },
  beforeCreate() {
    this.form = this.$form.createForm(this, {name: "register"});
  },
  mounted() {
    let _this = this;
    this.getRoleInfo();
    // let userInfo = this.$store.state.userInfo;
    let userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
    this.isShow(userInfo);
    window.Event.$on("menuLeft", val => {
      _this.menuLeft = val;
      if (_this.menuLeft != "menuDeaDolour") {
        _this.TableAdmin = 'TableAdmin';
        _this.butAdmin = 'butAdmin';
        _this.TableButSave = 'TableButSave';
        _this.TableButReset = 'TableButReset';
      } else if (_this.menuLeft == "menuDeaDolour") {
        _this.TableAdmin = 'TableAdmin1';
        _this.butAdmin = 'butAdmin1';
        _this.TableButSave = 'TableButSave1';
        _this.TableButReset = 'TableButReset1';
      }
    });
    // _this.menuLeft1 = _this.$store.state.menuLeft;
    _this.menuLeft1 = sessionStorage.getItem('menuLeft')
    if (_this.menuLeft1 != "menuDeaDolour") {
      _this.TableAdmin = 'TableAdmin';
      _this.butAdmin = 'butAdmin';
      _this.TableButSave = 'TableButSave';
      _this.TableButReset = 'TableButReset';
    } else if (_this.menuLeft1 == "menuDeaDolour") {
      _this.TableAdmin = 'TableAdmin1';
      _this.butAdmin = 'butAdmin1';
      _this.TableButSave = 'TableButSave1';
      _this.TableButReset = 'TableButReset1';
    }
  },
  methods: {
    onPageChange(current, pageSize) {
      this.pagination.current = current;
      this.pagination.pageSize = pageSize;
      this.getRoleInfo()
    },
    isShow(userInfo) {
      if (userInfo.permissions.includes("cf:sys:role:add")) {
        this.addShow = true;
      }
      if (userInfo.permissions.includes("cf:sys:role:remove")) {
        this.delShow = true;
      }
      if (userInfo.permissions.includes("cf:sys:role:edit")) {
        this.editShow = true;
      }
      if (userInfo.permissions.includes("cf:sys:role:permission")) {
        this.impShow = true;
      }
    },
    addRole() {
      this.form.resetFields();
      this.addVisible = true;
    },
    // 删除
    Delete(roleId) {
      let _this = this;
      api.roleRemove(null, roleId).then(res => {
        if (res.code == 200 && res.data == true) {
          this.$message.success("删除成功");
          this.getRoleInfo();
        } else {
          this.$message.error("删除失败");
          this.getRoleInfo();
        }
      });
    },
    // 编辑
    edit(id) {
      this.editVisible = true;
      this.getInfo(id);
    },
    // 授权
    impower(id) {
      this.tRoleId = id;
      this.impowerVisible = true;
      this.menuGetList(id);
      this.getPermissions(id);
    },
    // 获取角色权限
    getPermissions(roleId) {
      let _this = this;
      api.roleGetPermissions(null, roleId).then(res => {
        if (res.code == 200) {
          let arr = res.data.menus
          let arr1 = res.data.buttons
          let tmpList = arr.concat(arr1);
          const result = [...new Set(this.test)].filter((item) => new Set(eval(tmpList)).has(item));
          _this.checkedKeys = [...result];
        }
      })
    },
    // 获取菜单列表
    menuGetList() {
      let _this = this;
      menuApi.menuGetList().then(res => {
        if (res.code == 200) {
          _this.treeData = res.data;
          _this.deepList(_this.treeData);
        }
      })
    },
    deepList(data) {
      let _this = this;
      data.map((item) => {
        if (item.children && item.children.length > 0) {
          _this.deepList(item.children);
        } else {
          //test数组存放
          _this.test.push(item.id);
        }
      });
    },
    cancelImpower() {
      this.impowerVisible = false;
    },

    onBusinessSelectChange(selectedKeys, info) {
      // console.log('selectedKeys changed: ', selectedKeys);
      // console.log('info changed: ', info);
      // 已勾选子节点以及半勾选状态的父节点
      this.allSelectedNodes = selectedKeys.concat(info.halfCheckedKeys);
    },
    // 赋予角色权限
    addImpower(allSelectedNodes) {
      let _this = this;
      let roleId = _this.tRoleId;
      api.roleSetPermissions(null, {menuIds: allSelectedNodes, roleId: roleId}).then(res => {
        if (res.code == 200) {
          this.$message.success("授权成功");
          // 关闭对话框
          _this.impowerVisible = false;
          // 重新执行一遍 在页面初始化加载时的语句，为了刷新数据
          this.getRoleInfo();
        } else {
          this.$message.error("授权失败");
          // 关闭对话框
          _this.impowerVisible = false;
          // 重新执行一遍 在页面初始化加载时的语句，为了刷新数据
          this.getRoleInfo();
        }
      })
    },
    // 根据id 获取角色详情 ->编辑回显数据
    getInfo(id) {
      let _this = this;
      _this.tRoleId = id;
      api.roleGetInfo(null, id).then(res => {
        if (res.code == 200) {
          this.form.setFieldsValue({
            status: res.data.status,
            roleName: res.data.roleName,
            remark: res.data.remark
          });
        }
      });
    },
    onChange(pageNumber) {
      console.log("Page: ", pageNumber);
    },
    getRoleInfo() {
      let _this = this;
      _this.Loading = true;
      let pageNum = _this.pagination.current;
      let pageSize = _this.pagination.pageSize;
      api
          .roleGetList(null, {pageNum: pageNum, pageSize: pageSize})
          .then(res => {
            _this.Loading = false;
            if (res.code == 200) {
              _this.pagination.total = res.data.totalCount;
              _this.data = res.data.data;
              _this.data.forEach((e, v) => {
                if (e.status == 0) {
                  e.status = '正常'
                } else if (e.status == 1) {
                  e.status = '停用'
                }
              })
            }
          });
    },
    // 添加角色
    closeAddRole() {
      let _this = this;
      _this.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          api.roleAdd(null, values).then(res => {
            if (res.code == 200) {
              this.$message.success("添加成功");
              // 关闭对话框
              _this.addVisible = false;
              // 重新执行一遍 在页面初始化加载时的语句，为了刷新数据
              this.getRoleInfo();
            } else {
              this.$message.error("添加失败");
              // 关闭对话框
              _this.addVisible = false;
              // 重新执行一遍 在页面初始化加载时的语句，为了刷新数据
              this.getRoleInfo();
            }
          });
        }
      });
    },
    // 编辑角色
    closeEditRole() {
      let _this = this;
      _this.form.validateFieldsAndScroll((err, values) => {
        values.id = _this.tRoleId;
        if (!err) {
          api.roleEdit(null, values).then(res => {
            if (res.code == 200) {
              this.$message.success("编辑成功");
              // 关闭对话框
              _this.editVisible = false;
              // 重新执行一遍 在页面初始化加载时的语句，为了刷新数据
              this.getRoleInfo();
            } else {
              this.$message.error("编辑失败");
              // 关闭对话框
              _this.editVisible = false;
              // 重新执行一遍 在页面初始化加载时的语句，为了刷新数据
              this.getRoleInfo();
            }
          });
        }
      });
    },
    addReturnReset() {
      this.form.resetFields();
    },
    onExpand(expandedKeys) {
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    onCheck(checkedKeys) {
      this.checkedKeys = checkedKeys;
    },
    onSelect(selectedKeys, info) {
      this.selectedKeys = selectedKeys;
    }
  }
};
</script>

<style lang="scss" scoped>
.whole {
  position: relative;

  .Loading {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .crumbs {
    display: flex;
    padding-left: 31px;
    margin-top: 14px;

    a,
    area,
    button,
    [role="button"],
    input:not([type="range"]),
    label,
    select,
    summary,
    textarea,
    .ant-breadcrumb {
      font-family: MicrosoftYaHei;
      font-size: 18px;
      font-weight: normal;
      font-stretch: normal;
      letter-spacing: 0px;
      color: #4d4d4d;
    }

    .ant-breadcrumb > span:last-child a {
      font-family: MicrosoftYaHei;
      font-size: 18px;
      font-weight: normal;
      letter-spacing: 0px;
      color: #1e7eff;
    }
  }

  .jiange {
    display: inline-block;
    width: 10px;
  }

  .rouView {
    position: absolute;
    left: 50%;
    transform: translate(-450px);
    top: 40px;
  }

  .roleTable {
    margin-left: 25px;
    min-height: 562px;
    width: 1560px;
    background: #ffffff;
    border: 1px solid #c4d7e1;
    border-radius: 6px;
  }

  .addUser {
    width: 80%;
    display: flex;
    justify-content: flex-start;
    margin: 10px 0;
    margin-left: 30px;

    .userAbut {
      width: 120px;
      height: 36px;
      border-radius: 30px;
      background-color: #0078b5;
      font-size: 17px;
    }
  }

  .comAddUser {
    position: absolute;
    left: 10%;
    top: 20px;
  }

  .addUserTitle {
    width: 100%;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 18px;
    border-bottom: 1px solid #d5d5d5;

    .title_text {
      margin-left: 20px;
    }

    .title_close {
      margin-right: 20px;
    }
  }

  .addForm {
    width: 100%;

    .surName {
      display: flex;
      justify-content: flex-end;
    }

    .radioStatus {
      display: flex;
      height: 60px;

      .status {
        float: left;
      }

      .ant-form-item-control {
        line-height: 60px !important;
      }
    }
  }

  .aModal {
    .butSave {
      width: 94px;
      height: 30px;
      border-radius: 30px;
      background-color: #0078b5;
      font-size: 16px;
      color: #fff;
      margin-right: 40px;
    }

    .butReset {
      width: 94px;
      height: 30px;
      border-radius: 30px;
      font-size: 16px;
      color: #0376b7;
      border: 1px solid #0376b7;
    }

    .addForm {
      width: 100%;

      .surName {
        display: flex;
        justify-content: flex-end;
      }

      .radioStatus {
        display: flex;
        height: 60px;

        .status {
          float: left;
        }

        .ant-form-item-control {
          line-height: 60px !important;
        }
      }
    }
  }

  .aModal1 {
    .butSave {
      width: 94px;
      height: 30px;
      border-radius: 30px;
      background-color: #0078b5;
      font-size: 16px;
      color: #fff;
      margin-right: 40px;
    }

    .butReset {
      width: 94px;
      height: 30px;
      border-radius: 30px;
      font-size: 16px;
      color: #0376b7;
      border: 1px solid #0376b7;
    }

    .addForm {
      width: 100%;

      .surName {
        display: flex;
        justify-content: flex-end;
      }

      .radioStatus {
        display: flex;
        height: 60px;

        .status {
          float: left;
        }

        .ant-form-item-control {
          line-height: 60px !important;
        }
      }
    }
  }

  .aModalImpower {
    .aTree {
      width: 95% !important;
      background-color: #f6f6f6 !important;
      display: flex !important;
      flex-direction: column !important;
      align-items: flex-start !important;
      margin: 0 auto !important;
    }

    ul {
      list-style-type: none;
    }

    .butSave {
      width: 94px;
      height: 30px;
      border-radius: 30px;
      background-color: #0078b5;
      font-size: 16px;
      color: #fff;
      margin-right: 40px;
    }

    .butReset {
      width: 94px;
      height: 30px;
      border-radius: 30px;
      font-size: 16px;
      color: #0376b7;
      border: 1px solid #0376b7;
    }
  }
}
</style>
<style>
.TableAdmin .ant-table-thead > tr > th .ant-table-header-column {
  color: #5a77b1;
}

.TableAdmin1 .ant-table-thead > tr > th .ant-table-header-column {
  color: #238cc3;
}

.TableAdmin .ant-table-thead > tr > th {
  background-color: #fff !important;
  border-bottom: 1px solid #5c78aa !important;
  color: #5a77b1 !important;
  font-size: 16px !important;
  font-weight: bold !important;
  border-top-left-radius: 10px !important;
  border-top-right-radius: 10px !important;
}

.TableAdmin1 .ant-table-thead > tr > th {
  background-color: #fff !important;
  border-bottom: 1px solid #238cc3 !important;
  color: #238cc3 !important;
  font-size: 16px !important;
  font-weight: bold !important;
  border-top-left-radius: 10px !important;
  border-top-right-radius: 10px !important;
}

.ant-spin-nested-loading {
  width: 1488px !important;
  margin: 0 auto;
}

.roleTable {
  position: relative !important;
}

.ant-spin-nested-loading {
  position: static !important;
}

.ant-spin-container {
  position: static !important;
}

.aModal .ant-form-item-label, .aModal1 .ant-form-item-label {
  display: flex !important;
  width: 80px !important;
}

.aModal .ant-input, .aModal1 .ant-input {
  height: 36px !important;
}

.aModal .ant-form-item-control, .aModal1 .ant-form-item-control {
  width: 360px !important;
}

.aModal #register_remark, .aModal1 #register_remark {
  height: 200px !important;
}

.aModal .aFormItem.ant-row.ant-form-item, .aModal1 .aFormItem.ant-row.ant-form-item {
  margin-bottom: 0 !important;
  height: 60px !important;
}

.aModal .radioStatus.ant-row.ant-form-item .ant-form-item-control, .aModal1 .radioStatus.ant-row.ant-form-item .ant-form-item-control {
  margin-top: 10px !important;
}

.aModal .ant-modal-title, .aModal1 .ant-modal-title {
  display: flex !important;
}

.aModal .ant-modal-content, .aModal1 .ant-modal-content {
  width: 480px !important;
  height: 480px !important;
  box-shadow: 0px 0px 20px 0px rgba(0, 120, 182, 0.6) !important;
  border-radius: 10px !important;
}

.aModal .ant-modal-body, .aModal1 .ant-modal-body {
  padding: 0 !important;
  padding-top: 20px !important;

}

.whole .aModalImpower .aTree {
  height: 220px !important;
  overflow-y: auto !important;
  /* overflow-x: hidden !important; */
}

.aModal .addForm.ant-form.ant-form-horizontal.ant-form-hide-required-mark, .aModal1 .addForm.ant-form.ant-form-horizontal.ant-form-hide-required-mark {
  display: flex !important;
  flex-direction: column !important;
  align-items: center !important;
}

.aModalImpower .ant-modal-content {
  width: 480px !important;
  box-shadow: 0px 0px 20px 0px rgba(0, 120, 182, 0.6) !important;
  border-radius: 10px !important;
}
</style>
